package edu.vt.ece4564.bluetendance.attendance;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import edu.vt.ece4564.bluetendance.database.DatabaseConnector;

public class AttendanceRegistrationHandler implements Runnable {
	private HttpServletResponse response;
	private int classMeetingID;
	private List<Integer> students;

	public AttendanceRegistrationHandler(HttpServletResponse response, int classMeetingID, String students) {
		this.response = response;
		this.classMeetingID = classMeetingID;

		this.students = new ArrayList<Integer>();
		String[] studentsSplit = students.split(";");
		for (String student : studentsSplit) {
			this.students.add(Integer.parseInt(student));
		}
	}

	@Override
	public void run() {
		DatabaseConnector dc = DatabaseConnector.get();

		for (Integer studentID : this.students) {
			dc.commandText = "call SP_RegisterAttendance('" + classMeetingID + "', '" + studentID + "');";

			try {
				if (dc.executeNonQuery() == 0) {
					response.getWriter().write("There was an error while updating attendance records.");
				}
				else {
					response.getWriter().write("Addendance records were successfully updated.");
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
